﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;

namespace Flagwind.Web.Http.Controllers
{
	public class DirectoryController
	{
		#region 成员字段

		private string _basePath;

		#endregion

		#region 构造方法

		public DirectoryController()
		{
		}

		#endregion

		#region 公共属性

		public string BasePath
		{
			get
			{
				return _basePath;
			}
			set
			{
				if(string.IsNullOrWhiteSpace(value))
				{
					throw new ArgumentNullException();
				}

				var text = value.Trim();

				_basePath = text + (text.EndsWith("/") ? string.Empty : "/");
			}
		}

		#endregion

		#region 公共方法

		public async Task<IEnumerable<Flagwind.IO.PathInfo>> Get(string path, string pattern = null)
		{
			if(string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentNullException("path");
			}

			return await Flagwind.IO.FileSystem.Directory.GetChildrenAsync(this.GetDirectoryPath(path), GetPattern(pattern));
		}

		[HttpGet]
		public async Task<IEnumerable<Flagwind.IO.FileInfo>> Files(string path, string pattern = null)
		{
			if(string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentNullException("path");
			}

			return await Flagwind.IO.FileSystem.Directory.GetFilesAsync(this.GetDirectoryPath(path), GetPattern(pattern));
		}

		#endregion

		#region 私有方法

		private string EnsureBasePath(out string scheme)
		{
			string path;

			if(Flagwind.IO.Path.TryParse(this.BasePath, out scheme, out path))
			{
				return (scheme ?? Flagwind.IO.FileSystem.Scheme) + ":" + (path ?? "/");
			}

			scheme = Flagwind.IO.FileSystem.Scheme;
			return scheme + ":/";
		}

		private string GetDirectoryPath(string path)
		{
			string scheme;
			string basePath = this.EnsureBasePath(out scheme);

			if(string.IsNullOrWhiteSpace(path))
			{
				return basePath;
			}

			path = Uri.UnescapeDataString(path).Trim();

			if(path.StartsWith("/"))
			{
				return scheme + ":" + path + (path.EndsWith("/") ? string.Empty : "/");
			}
			else
			{
				return Flagwind.IO.Path.Combine(basePath, path) + (path.EndsWith("/") ? string.Empty : "/");
			}
		}

		private string GetPattern(string pattern)
		{
			if(string.IsNullOrWhiteSpace(pattern))
			{
				return null;
			}

			return pattern.Trim();
		}

		#endregion
	}
}